# -*- coding: utf-8 -*-
# @Time   : 2024-03-14 17:58
# @Author : 大龙 🚀

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
from utils.tools import urlencode


class HunanBhqrmzfAacaPolicy(BaseTaxPolicySpider):
    name = 'hunan_bhqrmzf_aaca_policy'

    province = "湖南省"
    city = "郴州市"
    county = "北湖区"
    park = ""
    source = "北湖区人民政府"

    def start_requests(self):
        url = 'http://www.czbeihu.gov.cn/zwgk/zwxxgkml/qzfxxgkml/gfxwj/default.htm'
        cookies = {
            "HttpOnly": "",
            "MM_mq4qQammP3BAe": "625c2a69b6b926f105fd2295522f9ffd",
            "CTCC_HTTP_COOKIE": "c89adba9c51bb6532953d6bd57c110ab",
            "MM_1xL8nvQydGCE0": "TkR2T3I3SlBEMGlGQW9qcZhwKK3HJYAZqiwFW7fPkFAeAWKf6rGkygL2DLIQljQAJrc1E0O75NCCSOszBqrJNkjHs4M7xjnEQDgxX3BZQcuVBjWlbE+azVUKcIpQno6BuDt5rPCTpzyRN3Qd4Zbjx+Jv0bSN5nyeHHzWzLlwGaQtpA9PVHfK7jytf/jkW6dV8Ag292bUH+JCLCm2iBC8UMBKfPzgPSEzPvRo85PR0y73FIzuJ/ChQ2WZV+S2yVTHl7LJdoMqVr1mq+3/LsfJNjsNGQisyVk1cuKzXsmZSqnZxLip97Bva4oiGhTdRvPOoEsWIj2Z3AMGNg6lTtQkdQgeNkWx86Hcd0HX3PU43iZsPju6o3PEBvuLXz0bnwDWV5AvTLzldYBYFPD95xVmGiM027WC/UU75oefTsSm8a4=",
            "arp_scroll_position": "1167"
        }
        yield scrapy.Request(url, callback=self.parse_list, cookies=cookies)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath("//ul/li[not(@id)]//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=10] | //dl/dt[not(@id)]//a[contains(@href, 'htm') or @title]/ancestor::dt[string-length(string(.))>=10] | //tr/td[not(@id)]//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=10]"):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = response.xpath("""//div[@id="pagination"]/span/text()""").re_first(r"""(\d+)页""")
            for page_num in range(1, int(total_page) + 1):
                url = f'http://www.czbeihu.gov.cn/zwgk/zwxxgkml/qzfxxgkml/gfxwj/default_{page_num}.htm'
                yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline
    cmdline.execute("scrapy crawl hunan_bhqrmzf_aaca_policy".split())
